import * as React from 'react'
import './index.css'; // 确保CSS类与Vue版本匹配 
import { useState,useEffect } from 'react'
import { useNavigate  } from 'react-router-dom';
import { Uploader,Toast  } from 'react-vant';
import bannerPng from '../assets/images/banner.png'
import deletePng from "../assets/icons/delete.png"
import uploadImg from "../assets/icons/uploadImg.png"
import moneyImg from '../assets/icons/money.png'
import selectIconImg from '../assets/icons/selectIcon.png'


import Header from '../components/header.jsx'
import Loading from '../components/loading.jsx'

// import { AI } from '../lib/aonweb/aon-web.es.js'
import { AI, AIOptions, User} from 'aonweb'
import { getTemplate } from '../lib/getTemplate'
import { use } from '../../node_modules/i18next/index.v4';
import bus from '../eventBus.js';

function Pages() {
  const navigateTo  = useNavigate();
  const [imgUrl, setImgUrl] = useState('');  
  const [submitImgUrl,setSubmitImgUrl]=useState('');
  const [logoText, setLogoText] = useState('');  
  const [showError, setShowError] = useState(false); 
  const [showLoading,setShowLoading] = useState(false)
  const [templateId, setTemplateId] = useState(null); // 假设templateId的初始状态是null 
  const [prompt , setPrompt ] = useState("A figure engulfed in light, with intense glow radiating fiercely behind."); // 假设templateId的初始状态是null 
  const [swapImgUrl,setSwapImgUrl]=useState('')  //上传的图片
//   const templateList =[
//     {
//         "id": "1",
//         "image": template1,
//         "prompt": "A figure engulfed in light, with intense glow radiating fiercely behind."
//     },
//     {
//         "id": "2",
//         "image":template2,
//         "prompt": "A person standing amidst a storm, lightning crackling in the background."
//     },
//     {
//         "id": "3",
//         "image": template3,
//         "prompt": "A silhouette surrounded by swirling mist, ethereal light illuminating the scene behind."
//     },
//     {
//         "id": "4",
//         "image":template4,
//         "prompt": "A figure emerging from a dense forest, with beams of sunlight creating a radiant backdrop."
//     }
// ]
  const [templateList,setTemplateList]=useState('')  //模板列表

// hook API 加载后事件
useEffect(() => {  
    // 组件挂载后执行的函数  
    console.log(window.appData,'全局数据')
    getTemplateList()
    login()
  }, []); // 传入空数组以确保只在组件首次渲染后执行 


const getTemplateList= async()=> {
    try {
      const list = await getTemplate()
      setTemplateList(list)
      // templateList.value = list
      setSwapImgUrl(list[0].image)
      console.log("imageUrl", swapImgUrl)
    } catch (error) {
      console.log(error)
    }
}

const selectTemplate = (id, image, prompt) => {  
  setTemplateId(id)
  // setPrompt(prompt);  
  setSwapImgUrl(image)
  // 这里可以添加其他逻辑，比如处理prompt或image  
}; 

function goToComplete(url) {
    navigateTo('/created?url='+url)
  }
  
  const onOversize = (file) => {
    console.log(file);
    // Toast('文件大小不能超过 30MB');
    Toast(window.appData.common.text.img-max-tip);
  };

  const handleLogoTextChange = (e) => {  
    setLogoText(e.target.value);  
  };  
  
  const deleteImg = () => {  
    if (imgUrl) {
      const formData = new FormData();
      formData.append('file', imgUrl);
  
      // 删除文件
      formData.delete('file');
      setImgUrl('')
      setSubmitImgUrl('')
      
      console.log('File deleted:', formData.get('file'));
    } else {
      console.log('No file to delete')
    }
    setImgUrl('');  
  };  
  
  //表单提交逻辑
  const formSubmit = async () => {
    console.log(submitImgUrl, swapImgUrl)
    if ( !imgUrl || !swapImgUrl) {
      setShowError(true)
      setTimeout(() => {
        setShowError(false)
      }, 3000)
      return
    }
    setShowLoading(true)
    // showLoading.value = true
    try {
      // const file = await uploadFileByUrl(imgUrl)
      // debugger;
      // setSubmitImgUrl(file.data)

      // AI 使用方法
      const ai_options =new AIOptions({
        //Please replace with your own API key or jwt token.
        appId: window.appData.appid,
        // host: "http://localhost:8080"
      })
      debugger
      const aonet = new AI(ai_options)
      const data = {
        input: {
            "swap_image": submitImgUrl,
            "target_image": swapImgUrl,     
        }
      }
      console.log("formSubmit data", data)
      let price = 10
      let jsonString=''
      let response = await aonet.prediction("/predictions/ai/face-swap", data,price)
      console.log("test", response)
      if (response && response.code == 200 && response.data) {
        response = response.data
        jsonString = JSON.stringify(response.task)
        console.log("response\n", jsonString);    
      }
      
      if (response.task.exec_code == 200 && response.task.is_success) {
        // showLoading.value = false
        setShowLoading(false)
        let url = response.output
        if (Array.isArray(response.output)) {
          url = response.output && response.output.length && response.output[0]
        }
        if (typeof url == 'object' || typeof url == 'Object') {
          return
        }
        
        goToComplete(url)
      } else {
        setShowLoading(false)
        Toast(jsonString)
      }
    } catch (error) {
      setShowLoading(false)
      Toast.fail(error.message)
    }
  }


  const afterRead=async (file:File)=>{
    const formData = new FormData();
    formData.append('file', file);
    console.log(formData, file)

    // 调用上传接口
    // uploadFile(formData).then(res => {
    //   console.log(res);
    //   if (res.code == 200 && res.data && res.data.length) {
    //     setSubmitImgUrl(res.data)
    //   }

    // }).catch(err => {
    //   Toast('image upload failed');
    //   console.log(err);
    // });

    setImgUrl(URL.createObjectURL(file))
    const fileResult = await uploadFileByUrl(imgUrl)
    debugger;
    setSubmitImgUrl(fileResult.data)

  }
  // 上传接口
  const uploadFile = async (formData) => {
    const response = await fetch('https://tmp-file.aigic.ai/api/v1/upload?expires=1800&type=image/png', {
      method: 'POST',
      body: formData
    });

    const data = await response.json();
    console.log(data,'上传结果');
    return data;
  }; 
  // 通过上传本地路径或者在线地址
 const  uploadFileByUrl=(url)=>{
    return fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const formData = new FormData();
      formData.append('file', blob);
      return uploadFile(formData)
    })
}

 const login=async()=> {
    // showLoading.value = true
    console.log('index login')
    let user = new User()
    let temp = await user.islogin()
    if (!temp) {
      console.log('index islogin')
      await user.login((acc,userId,error) => {
        // showLoading.value = false
        setShowLoading(false)
        console.log("getWeb3 account",acc)
        console.log("getWeb3 userId",userId)
        if (error) {
          console.log("getWeb3 error",error)
            login()
        } else {
          bus.emit('get_balance',"login")
          console.log('index islogin sssss',temp)
        }
      })
    } else {
      // showLoading.value = false
      bus.emit('get_balance',"login");
      console.log('index islogin sssss',temp)
    }
  }

  return (
    <>
    {/* <Header/> */}
    <Loading showLoading={showLoading} />
        <div className="container">  
      <div className='bannerWrap'>
        <img className="banner" src={bannerPng} alt="" /> 
        <span className='bannertxt'>AI智能换装</span> 
      </div>
      <div className="uni-form-item uni-column">  
        <div className="title">Upload your photos</div>  
        <div className="content">  
          {imgUrl ? (  
            <div className="upload upload-done">  
              <img className="upload-res" src={imgUrl} alt="" />  
              <img  
                className="deleteIcon"  
                onClick={deleteImg}  
                src={deletePng}  
                alt=""  
              />  
            </div>  
          ) : (  
            <Uploader  
              maxSize={30 * 1024 * 1024} // 假设Uploader组件接受maxSize属性  
              onOversize={onOversize}  
              // afterRead={afterRead}  
              // upload={afterRead}
              upload={afterRead}
              className="upload upload-before"  
            >  
              <img className="uploadIcon" src={uploadImg} alt="" />  
              <span>limit 30MB per file</span>  
            </Uploader>  
          )}  
        </div>  
      </div>  
      {/* <div className="uni-form-item uni-column">  
        <div className="title">Customize your clothing logo</div>  
        <div className="content">  
          <input  
            value={logoText}  
            onChange={handleLogoTextChange}  
            placeholder="Please enter the logo text on your clothes"  
          />  
        </div>  
      </div>   */}

      <div className="uni-form-item uni-column">  
            <div className="title">Choose your template</div>  
            {templateList.length > 0 && (  
                <div className="templateCon">  
                    {templateList.map((item, index) => (  
                        <div  
                            key={item.id} // 通常我们会使用唯一的id作为key，而不是索引  
                            className={`template_item ${Number(item.id) === templateId ? 'templateActive' : ''}`}  
                            onClick={() => selectTemplate(Number(item.id), item.image, item.prompt)}  
                        >  
                            <img src={item.image} alt="" />  
                            <div  
                                className={`isActiveIcon ${Number(item.id) === templateId ? 'active' : ''}`}  
                            >  
                                {Number(item.id) === templateId && (  
                                    <img src={selectIconImg} alt="" />  
                                )}  
                            </div>  
                        </div>  
                    ))}  
                </div>  
            )}  
        </div> 
    

      
      {showError && (  
        <div className="uni-form-item error-text">  
          <div className="content">Please Upload your photos</div>  
        </div>  
      )}  
      <div className="bottom_btn">  
        <div className="spendCount">  
          <img className="icon" src={moneyImg} alt="" />  
          <span>-8</span>  
        </div>  
        <button className="submitBtn" onClick={formSubmit}>  
          <span>生成图片</span>  
        </button>  
      </div>  
    </div>  
  
   </>
  );
}

export default Pages;
